import os
import re
import subprocess
#video_path, first_result
def play_video_from_timestamp(video_path, result):
    """在指定时间区间内播放视频"""
    try:
        # 查找VLC安装路径
        vlc_path = "C:\Program Files\VideoLAN\VLC\\vlc.exe"                    
            
        # 时间戳格式转换
        def parse_timestamp(ts):
            """将时间戳字符串转换为秒数"""
            if isinstance(ts, str):
                # 处理格式为"00:03:06.000"的字符串
                h, m, s = ts.split(':')
                s = float(s)
                return int(h)*3600 + int(m)*60 + s
            elif isinstance(ts, (int, float)):
                # 已经是秒数
                return ts
            else:
                raise ValueError(f"无法解析的时间戳格式: {ts}")
                
        start_seconds = parse_timestamp(result['timestamp_s'])
        end_seconds = parse_timestamp(result['timestamp_e'])
        
        # 构建播放命令
        # 标准化路径并转换为正斜杠
        if not os.path.exists(video_path):
            raise FileNotFoundError(f"视频文件不存在: {video_path}")
            
        print(f"VLC路径: {vlc_path}")
        print(f"视频路径: {video_path}")
        print(f"开始时间: {start_seconds}")
        print(f"结束时间: {end_seconds}")
        
        # 构建播放命令
        command = [
            vlc_path,
            video_path,
            f'--start-time={start_seconds}',
            f'--stop-time={end_seconds}',
            '--no-sub-autodetect-file'
            ,'--loop'
        ]
        
        # 启动播放器并获取进程对象
        print("执行命令:", command)
        process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return process
        
    except Exception as e:
        raise Exception(f"播放视频失败: {str(e)}")

def find_word_in_files(word, search_dir=None):
    if search_dir is None:
        search_dir = os.path.join(os.path.dirname(__file__), 'pool')
    results = []
    
    # 递归遍历目录下的视频文件
    for root, dirs, files in os.walk(search_dir):
        for filename in files:
            if filename.endswith('.mp4') or filename.endswith('.mkv') or filename.endswith('.rmvb'):
                # 获取视频文件相对路径
                video_path = os.path.join(root, filename)
                # 查找对应的字幕文件
                txt_file = os.path.splitext(filename)[0] + '.txt'
                txt_path = os.path.join(root, txt_file)
                
                if os.path.exists(txt_path):
                    with open(txt_path, 'r', encoding='utf-8') as f:
                        for line in f:                        
                            if word in line:
                                # 提取时间戳（格式为[00:03:06.000 --> 00:03:10.000]）
                                timestamp_match = re.search(r'\[(\d{2}:\d{2}:\d{2}\.\d{3} --> \d{2}:\d{2}:\d{2}\.\d{3})\]', line)
                                if timestamp_match:
                                    start_time, end_time = timestamp_match.group(1).split(' --> ')
                                    # 保存相对路径
                                    rel_path = os.path.relpath(video_path, search_dir)
                                    results.append({
                                        'file': rel_path,
                                        'timestamp_s': start_time,
                                        'timestamp_e': end_time,
                                        'line': line.strip()
                                    })
    return results
